<template>
  <div class="flex-between height100 tw-font-medium">
    <div class="tw-flex-1 flex-column ">
      <div class="tw-h-80 flex-middle tw-pl-32 color-white tw-mb-24 font-normal">
        <p class="click flex-middle" @click="router.back()">
          <el-icon color="#fff" size="24">
            <ArrowLeft/>
          </el-icon>
          <span class="tw-ml-8 tw-mr-24 font-small">返回</span>
        </p>
        <!--        <span>-->
        <!--        {{ currentStudy.name }}-->
        <!--        </span>-->
      </div>
      <div id="videoMaterial" class="width100 tw-flex-1">

      </div>
    </div>

    <div class="tw-w-440  tw-bg-[#121212] tw-overflow-y-auto">
      <p class="tw-h-80 flex-middle tw-text-[#999999] font-normal tw-mb-20 tw-ml-20">课程目录</p>
      <div v-for="(item,index) in dataArr " :key="index" class="font-normal">
        <div class="tw-bg-[#1e2227] tw-mx-20  tw-h-56 color-white flex-between-center tw-px-24 border-box click"
             @click="item.isShow=!item.isShow">
          <span>{{ item.name }}</span>
          <el-icon :class="item.isShow?'tw-rotate-180 ':''">
            <ArrowDown/>
          </el-icon>
        </div>
        <div v-show="item.isShow">
          <div v-for="(childrenItem,childrenIndex) in item.children" :key="index"
               class="hover-father tw-px-24 border-box tw-pt-20"
               @click="changeCourse(childrenItem) ">
            <div
                class="  flex title-bor click font-small">
              <span :class="currentStudy.name==childrenItem.name?'tw-text-[#04addb]':'tw-text-[#999999]'"
                    class="tw-w-43 tw-pr-10 tw-text-right">{{
                  childrenIndex < 9 ? '0' + (childrenIndex + 1) : childrenIndex + 1
                }}</span>
              <div style="border-bottom: 1px solid #202020;flex: 1">
                <span :class="currentStudy.name==childrenItem.name?'tw-text-[#04addb]':'tw-text-[#CBCBCB] hover-color'"
                      class="font-small">  {{
                    childrenItem.name
                  }}</span>
                <div class="tw-mt-10 flex-middle font-mini tw-pb-20">
                  <p v-if="childrenItem.videoListenStatus==0"
                     class="tw-w-16 tw-h-16 study-status study-none tw-rounded-full border-box"></p>
                  <p v-if="childrenItem.videoListenStatus==1">
                    <img alt="" class="tw-w-16 tw-h-16 tw-mr-8" src="@/assets/images/study/study-learning.png">
                  </p>
                  <p v-if="childrenItem.videoListenStatus==2"
                     class="tw-w-16 tw-h-16 tw-bg-[#04addb] tw-rounded-full"></p>
                  <p v-if="childrenItem.type=='video'" class="tw-text-[#9598a2]  tw-ml-8 ">
                    <span>{{ courseBase.courseStudyType[childrenItem.type] }}</span>
                    <span class="tw-mx-9">|</span>
                    <span>{{

                            formatNumber(childrenItem.videoDuration/60,0)
                      }}分钟</span>
                  </p>
                  <p v-if="childrenItem.type=='live'" class="tw-text-[#9598a2]  tw-ml-8 ">
                    <span>{{ courseBase.courseStudyType[childrenItem.type] }}</span>
                    <span class="tw-mx-9">|</span>
                    <span>{{
                        formatNumber(childrenItem.videoDuration/60,0)
                      }}分钟</span>
                  </p>

                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, defineModel, reactive, ref, watch} from "vue";
import {ArrowDown, ArrowLeft} from "@element-plus/icons-vue";
import {getVideoHistory, saveVideoProgress} from "@/api/study.js";
import dayjs from "dayjs";
import {useRouter} from 'vue-router';
import {courseBase} from "@/common/course-base.js";
import {formatNumber} from "@/utils/common.js";
import {handleAutoCloseMessage} from "@/utils/elementUtil.js";

const router = useRouter();
const videoComponent = ref();
let currentItem = defineModel()
let currentStudy = ref({})
let data = reactive({
  videoId: currentStudy.value.typeAssoId,
  videoDuration: 0,
  courseId: currentStudy.value.id,
  startStudyTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  endStudyTime: 0,
  time: null,
  historyTime: 0,
  recording: 1
})
let props = defineProps({
  dataArr: {
    type: Array,
    default: []
  },
  orderItemId: {
    type: Number,
  },
  courseId: {
    type: Number,
  }
})
let emit = defineEmits(['chengStudy'])
watch(() => props.dataArr, (val) => {
  currentStudy.value = val[0].children.find(item => item.id == currentItem.value)
  emit('chengStudy', currentStudy.value)
  videoHistory()
  initCkPlay()
})
let videoObject = computed(() => {
  return {
    container: "#videoMaterial", //容器的ID或className
    logo: null,
    loop: false, //播放结束是否循环播放
    seek: data.historyTime, //默认跳转的时间
    autoplay:true,
    menu: [
      {
        title: 'ckplayer',
        link: 'http://www.ckplayer.com',
        underline: true
      },
      {
        title: '播放/暂停',
        click: 'player.playOrPause',
      },
      {
        title: '外部js',
        click: 'helle',
        underline: true
      },
      {
        title: '关于视频',
        click: 'aboutShow'
      }
    ],
    video: currentStudy.value.videoUrl
  }
})

const goBack = () => {

}
const destroyVideo = () => {
  if (videoComponent.value) {
    try {
      // 停止所有视频播放
      const videoElements = document.querySelectorAll('video');
      videoElements.forEach(video => {
        video.pause();
        video.src = '';
        video.load();
      });

      // 清空容器
      const container = document.querySelector("#videoMaterial");
      if (container) {
        container.innerHTML = '';
      }

      videoComponent.value = null;
    } catch (error) {
      console.log('清理播放器失败:', error);
    }
  }
}

// 添加防抖函数
let debounceTimer = null;
const debounce = (fn, delay = 300) => {
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
  debounceTimer = setTimeout(() => {
    fn();
    debounceTimer = null;
  }, delay);
}

const initCkPlay = (e) => {
  // 清理所有相关定时器
  clearAllTimers();

  // 使用防抖包装视频初始化
  debounce(() => {
    destroyVideo();
    videoComponent.value = new ckplayer(videoObject.value);

    videoComponent.value.addListener("time", function (time) {
      data.videoDuration = time
      if (!data.time && data.recording == 2) {
        clearInterval(data.time); // 确保清理之前的定时器
        data.time = setInterval(() => {
          data.endStudyTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
          saveVideoTime()
        }, 10000)
      }
      data.recording++
    });

    videoComponent.value.addListener("ended", function (ended) {
      let nums = props.dataArr[0].children.findIndex(item => item.id == currentStudy.value.id)
      if (nums >= 0) {
        props.dataArr[0].children[nums].videoListenStatus = 2
      }
      clearInterval(data.time)
      clearInterval(data.timer)
      data.time = null
      data.timer = null
      data.videoDuration = currentStudy.value.videoDuration
      saveVideoTime()
      videoEnd()
    });
    videoComponent.value.addListener("duration", function (duration) {
    });
    videoComponent.value.addListener("flashplayer", function (flashplayer) {
    });
    videoComponent.value.addListener("pause", function (flashplayer) {
      data.recording = 2
      clearInterval(data.time)
      data.time = null
    });
  });
}

const saveVideoTime = (e) => {
  if (data.videoDuration >= data.historyTime) {
    let dataAll = {
      videoId: currentStudy.value.typeAssoId || currentStudy.value.videoId,
      videoDuration: data.videoDuration,
      courseId: props.courseId,
      orderItemId: props.orderItemId,
      startStudyTime: data.startStudyTime,
      endStudyTime: data.endStudyTime
    }
    saveVideoProgress(dataAll)
  }

}
const changeCourse = (item) => {
  clearAllTimers(); // 清理所有定时器
  destroyVideo();

  emit('chengStudy', item)
  currentStudy.value = item
  data.recording = 1
  videoHistory()
}
let timer = ref()
let tipsTime = ref(5)
let fiveTime = (nums) => {
  timer.value = setInterval(() => {
    if (tipsTime.value > 0 && tipsTime.value <= 5) {
      tipsTime.value--

    } else {
      clearInterval(timer.value)
      if (nums != props.dataArr[0].children.length - 1) {
        currentStudy.value = props.dataArr[0].children[nums + 1]
        initCkPlay()
      }

    }
  }, 1000)
}
// 播放下个视频
const videoEnd = () => {
  let nums = props.dataArr[0].children.findIndex(item => item.id == currentStudy.value.id)
  if (nums < props.dataArr[0].children.length - 1 && nums >= 0 && !timer.value) {
    handleAutoCloseMessage('当前视频已播放完', 'info', 5, true, '后播放下个视频', closeTimer)
    tipsTime.value = 5
    fiveTime(nums)
  }
}
const videoHistory = () => {
  let dataAll = {
    videoId: currentStudy.value.typeAssoId || currentStudy.value.videoId,
    courseId: props.courseId,
    orderItemId: props.orderItemId,
  }
  getVideoHistory(dataAll, (res) => {
    data.historyTime = res.data
    initCkPlay()
  })
}
const closeTimer = () => {
  clearInterval(timer.value)
  timer.value = null
}

// 添加清理所有定时器的函数
const clearAllTimers = () => {
  // 清理视频进度保存的定时器
  if (data.time) {
    clearInterval(data.time);
    data.time = null;
  }

  // 清理自动播放下一个视频的定时器
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }

  // 清理防抖定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer);
    debounceTimer = null;
  }

  // 重置相关状态
  data.recording = 1;
  tipsTime.value = 5;
}
</script>

<style lang='scss' scoped>
.title-bor {
  border-bottom: 1px solid rgba(0, 0%, 100%, .06);
}

.hover-father :hover .hover-color {
  color: #04addb !important;
}

.study-none {
  border: 1px solid #9598a2;
}
</style>

